import { defineComponent, onMounted, ref, watch, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import type { ECharts } from 'echarts'; // 引入官方类型

const PropsType = {
  id: String,
  className: {
    type: String,
    default: 'chart',
  },
  width: {
    type: String,
    required: true,
  },
  height: {
    type: String,
    required: true,
  },
  options: {
    type: Object,
    default: () => ({}),
  },
} as const;

export default defineComponent({
  name: 'Echarts',
  props: PropsType,
  setup(props, { expose }) {
    const chartRef = ref<HTMLElement>();
    // 2. 修正类型定义：明确为 ECharts实例 或 null
    const charts = {
      chart: null as ECharts | null,
    };

    const initChart = (data?: any, clearCaching = false) => {
      if (!charts.chart) {
        console.warn('[Echarts Component] 警告：ECharts 实例尚未初始化，暂不执行 setOption');
        return;
      }
      const targetData = data || props.options;
      targetData && charts.chart.setOption(targetData, clearCaching);
    };

    // 初始化实例
    onMounted(() => {
      // 检查DOM是否存在
      if (!chartRef.value) {
        console.error('[Echarts Component] 错误：图表容器DOM不存在');
        return;
      }
      // 检查地图是否注册
      if (!echarts.getMap('河北')) {
        console.error('[Echarts Component] 错误：河北地图未注册！请检查 hebei.js');
        return;
      }
      // 初始化ECharts实例
      charts.chart = echarts.init(chartRef.value, 'myTheme');
      initChart();
    });

    // 生命周期：销毁实例（保留你的防御逻辑）
    onBeforeUnmount(() => {
      if (charts.chart) {
        charts.chart.dispose();
        charts.chart = null;
      }
    });

    // 监听options变化
    watch(
      () => props.options,
      (val) => {
        val && initChart(val);
      },
      {
        deep: false,
        immediate: false,
      }
    );

    // 暴露接口（保留）
    expose({
      chartRef,
      initChart,
    });

    return () => {
      const { id, className, height, width } = props;
      return (
        <div
          ref={chartRef}
          id={id as string}
          class={className as string}
          style={{ height, width }}
        />
      );
    };
  },
});